package top.lingchen.blogapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.lingchen.blogapi.bean.Tag;
import top.lingchen.blogapi.mapper.TagMapper;
import top.lingchen.blogapi.service.TagService;
import top.lingchen.blogapi.vo.Result;
import top.lingchen.blogapi.vo.TagVo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author 凌宸
 * @create 2021-12-15 下午 10:07
 * @Description
 * @Version 1.0
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;


    /**
     * 根据文章 id 查找标签 tag
     * @param articleId
     * @return
     */
    @Override
    public List<TagVo> findTagsByArticleId(Long articleId) {
        // mybatis-plus 无法进行多表查询，我们需要自己写 sql
        List<Tag> tagList = tagMapper.findTagsByArticleId(articleId);
        return copyList(tagList);
    }

    @Override
    public Result hots(int limit) {
        /**
         * 1. 标签所拥有的文章数最多，就是最热标签
         * 2. 根据 tag_id 分组，计数，从大到小排列， 取前 limit 个
         */
        List<Long> hotTagIds = tagMapper.findHotsTagIds(limit);
        if(CollectionUtils.isEmpty(hotTagIds)){
            return Result.success(Collections.emptyList());
        }
        // 需要的是 tagId 和 tagName
        List<Tag> tagList = tagMapper.findTagsByTagIds(hotTagIds);
        return Result.success(copyList(tagList));
    }

    @Override
    public Result findAll() {
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Tag::getId, Tag::getTagName);
        List<Tag> tagList = tagMapper.selectList(wrapper);
        return Result.success(copyList(tagList));
    }

    @Override
    public Result getAllTagsDetail() {
        List<Tag> tagList = tagMapper.selectList(null);
        return Result.success(copyList(tagList));
    }

    @Override
    public Result getTagsDetailById(Long tagId) {
        return Result.success(copy(tagMapper.selectById(tagId)));
    }

    private List<TagVo> copyList(List<Tag> tagList){
        List<TagVo> tagVoList = new ArrayList<>();
        for(Tag tag : tagList){
            tagVoList.add(copy(tag));
        }
        return tagVoList;
    }

    private TagVo copy(Tag tag) {
        TagVo tagVo = new TagVo();
        BeanUtils.copyProperties(tag, tagVo);
        tagVo.setId(String.valueOf(tag.getId()));
        return tagVo;
    }
}
